package org.jaaksi.kottlindemo.hilt

import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton

// SingletonComponent对应之前的ApplicationComponent
@Module
@InstallIn(SingletonComponent::class)
class NetworkModule {

    // @Provides告诉Hilt如何生成OkHttpClient。对我们自己的类，我们可以给类的构造器声明@Inject，但是三方代码我们是无法修改的，使用Module+Provides解决
    @Singleton
    @Provides
    fun provideOkHttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .connectTimeout(20, TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.SECONDS)
            .writeTimeout(20, TimeUnit.SECONDS)
            .build()
    }

    // @Singleton作用域，全局共享，对应SingletonComponent。@ActivityScoped对应ActivityComponent，同一个Activity共享一个实例
    @Singleton
    @Provides
    fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
        return Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl("http://example.com/")
            .client(okHttpClient)
            .build()
    }
}

